import 'dart:async';
import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:provider/provider.dart';
import 'package:study_online/entity/TestQuestion.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/screen_util.dart';
import 'package:flutter/material.dart';
import 'package:study_online/global/colors.dart';
import 'package:study_online/global/myIcons.dart';
import 'package:study_online/pages/testPage/TestModel.dart';
import 'package:study_online/pages/testPage/TestViewModel.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  const MyApp({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        //appBar: AppBar(
        //  backgroundColor: Colors.black26,
        //  title: Text('container'),
        //),
        body: TestPage(),
      ),
    );
  }
}

class TestPage extends StatefulWidget {
  TestPage({Key key, this.paId, this.title, this.stuId}) : super(key: key);
  int paId;
  String title, stuId;

  @override
  _TestPageState createState() {
    return _TestPageState();
  }
}

class _TestPageState extends State<TestPage> {
  PageController pageController;
  int currentPage = 0, progressBarValue = 0, second = 0;
  String _minute = "00", _second = "00",_nextProblem="下一题";
  Timer t;
  List _problemList = [];
  List<List<int>> ans = [];

  TestQuestionList _testQuestionList = new TestQuestionList([]);

  @override
  void initState() {
    super.initState();
    _loadData();
    pageController = new PageController(
      initialPage: 0,
      keepPage: true,
    );
    pageController.addListener(() {
      double offset = pageController.offset;
      double page = pageController.page;
      //print("pageView 滑动的距离 $offset  索引 $page");
    });
    // TestQuestion _t1 = new TestQuestion('A', '111', 'A11#B11#C11#D11', "选择题");
    // TestQuestion _t2 = new TestQuestion('A', '111', '对#错', "判断题");
    // TestQuestion _t3 = new TestQuestion('A', '111', 'A11#B11#C11#D11', "多选题");
    // _testQuestionList.data.add(_t1);
    // _testQuestionList.data.add(_t2);
    // _testQuestionList.data.add(_t2);
    // _testQuestionList.data.add(_t2);
    // _testQuestionList.data.add(_t3);
    // _testQuestionList.data.add(_t1);
    t = Timer.periodic(Duration(milliseconds: 1000), (timer) {
      setState(() {
        this.second++;
        int tm = (this.second ~/ 60).toInt();
        int ts = this.second - tm * 60;
        _minute = tm < 10 ? "0" + tm.toString() : tm.toString();
        _second = ts < 10 ? "0" + ts.toString() : ts.toString();
      });
    });
  }

  @override
  void dispose() {
    super.dispose();
    t.cancel();
  }

  void _loadData() async {
    Response response = await getTestByPaId(widget.paId);
    print("###" + response.toString());
    var responseData = json.decode(response.toString());
    setState(() {
      _testQuestionList = TestQuestionList.formJson(responseData);
    });
  }

  Widget _topBar() {
    return Container(
      //width: ScreenUtil().setWidth(992),
      height: ScreenUtil().setHeight(107),
      margin: EdgeInsets.only(top: ScreenUtil().setHeight(98)),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.end,
        children: [
          Center(
            child: IconButton(
              icon: Icon(Icons.close, size: ScreenUtil().setSp(90)),
              onPressed: () {
                Navigator.pop(context);
              },
            ),
          ),
          SizedBox(width: ScreenUtil().setWidth(25)),
          Center(
            child: Text(
              '$_minute:$_second',
              style: TextStyle(
                fontSize: ScreenUtil().setSp(50),
                color: AppColors.subtext,
              ),
            ),
          ),
          SizedBox(width: ScreenUtil().setWidth(125)),
          Center(
            child: Text(
              '${progressBarValue + 1}/${_testQuestionList.data.length}',
              style: TextStyle(
                fontSize: ScreenUtil().setSp(46),
                color: Colors.black,
              ),
            ),
          ),
          SizedBox(width: ScreenUtil().setWidth(20)),
          Center(
            child: AnimatedContainer(
              duration: Duration(seconds: 1),
              width: ScreenUtil().setWidth(268),
              height: ScreenUtil().setHeight(30),
              child: ClipRRect(
                borderRadius: BorderRadius.all(
                    Radius.circular(ScreenUtil().setHeight(15))),
                child: LinearProgressIndicator(
                  value: (progressBarValue + 1) / _testQuestionList.data.length,
                  backgroundColor: Color(0xffFFF3EBEB),
                  valueColor: AlwaysStoppedAnimation<Color>(AppColors.primary),
                ),
              ),
            ),
          ),
          SizedBox(width: ScreenUtil().setWidth(45)),
          IconButton(
            icon: Icon(MyIcons.answerSheet),
            iconSize: ScreenUtil().setSp(90),
            onPressed: () {
              _showDialog();
            },
          ),
          SizedBox(width: ScreenUtil().setWidth(10)),
          IconButton(
            icon: Icon(
              MyIcons.threeDots,
              color: Colors.black,
            ),
            iconSize: ScreenUtil().setSp(90),
          ),
        ],
      ),
    );
  }

  Widget _labelWidget(int index) {
    return Container(
      width: ScreenUtil().setWidth(125),
      height: ScreenUtil().setWidth(125),
      decoration: BoxDecoration(
        color: _problemList[index] == 0 ? Colors.black12 : AppColors.yellow,
        borderRadius:
            BorderRadius.all(Radius.circular(0.5 * ScreenUtil().setWidth(125))),
      ),
      child: Center(
        child: Text(
          (index + 1).toString(),
          style: TextStyle(
              fontSize: ScreenUtil().setSp(60),
              color: Colors.white,
              fontWeight: FontWeight.bold),
        ),
      ),
    );
  }

  _showDialog() async {
    showModalBottomSheet(
      context: context,
      builder: (BuildContext context) {
        return Container(
          color: Color(0xff737373),
          child: Container(
            width: double.infinity,
            height: ScreenUtil().setHeight(740) +
                ScreenUtil().setWidth(155) * ((_problemList.length-1) ~/ 6),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(15), topRight: Radius.circular(15)),
            ),
            padding: EdgeInsets.all(ScreenUtil().setWidth(60)),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Container(
                  child: Row(
                    children: [
                      SizedBox(width: ScreenUtil().setWidth(420)),
                      Text(
                        '答题卡',
                        style: TextStyle(
                            fontSize: ScreenUtil().setSp(62),
                            color: Colors.black,
                            fontWeight: FontWeight.bold),
                      ),
                      SizedBox(width: ScreenUtil().setWidth(286)),
                      InkWell(
                        onTap: (){
                          Navigator.pop(context);
                        },
                        child: Icon(
                          Icons.close,
                          size: ScreenUtil().setSp(90),
                          color: Colors.black,
                        ),
                      )
                    ],
                  ),
                ),
                Align(
                  alignment: Alignment.bottomLeft,
                  child: Text(
                    widget.title == null ? 'tit' : widget.title,
                    style: TextStyle(
                      fontSize: ScreenUtil().setSp(50),
                      color: Colors.black45,
                    ),
                    textAlign: TextAlign.start,
                  ),
                ),
                Wrap(
                  spacing: ScreenUtil().setWidth(30),
                  runSpacing: ScreenUtil().setWidth(30),
                  children: _problemList
                      .asMap()
                      .keys
                      .map((index) => _labelWidget(index))
                      .toList(),
                ),
                InkWell(
                  onTap: () {
                    String s = "ABCD";
                    int num = 0;
                    List<int> ansList=[];
                    for (int i = 0; i < _testQuestionList.data.length; ++i) {
                      String tp = "";
                      for (int j = 0; j < 4; ++j)
                        if (ans[i][j] == 1) tp += s[j];
                      if (tp == _testQuestionList.data[i].quAn) {
                        ++num;
                        ansList.add(1);
                      }
                      else
                        ansList.add(0);
                    }
                    Provider.of<TestViewModel>(context, listen: false).insert(
                        widget.paId,
                        widget.stuId,
                        1.0 * num / _testQuestionList.data.length,
                        1.0 * num / _testQuestionList.data.length*100,
                        _testQuestionList.data.length,
                        num,
                        ansList,
                        widget.title,
                        int.parse(_minute),
                        int.parse(_second),
                    );
                  },
                  child: Container(
                    height: ScreenUtil().setHeight(138),
                    width: ScreenUtil().screenWidth -
                        2 * ScreenUtil().setWidth(60),
                    decoration: BoxDecoration(
                      gradient: LinearGradient(
                          begin: Alignment.topLeft,
                          end: Alignment.centerRight,
                          stops: [0.0, 1.0],
                          colors: [Color(0xc42dca97), Color(0xff2dca97)]),
                      borderRadius: BorderRadius.all(
                          Radius.circular(0.5 * ScreenUtil().setHeight(138))),
                    ),
                    child: Center(
                      child: Text(
                        '提交练习',
                        style: TextStyle(
                          fontSize: ScreenUtil().setSp(56),
                          fontWeight: FontWeight.bold,
                          color: Colors.white,
                        ),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  Widget _problems(int index) {
    List<String> _optionList = [];
    _optionList = _testQuestionList.data[index].quOption.split("#");
    return Container(
      margin: EdgeInsets.fromLTRB(ScreenUtil().setWidth(52),
          ScreenUtil().setHeight(110), ScreenUtil().setWidth(52), 0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '${index + 1}.${_testQuestionList.data[index].quStyle}',
            style: TextStyle(
              fontSize: ScreenUtil().setSp(43),
              color: Colors.black,
            ),
            textAlign: TextAlign.start,
          ),
          SizedBox(
            height: ScreenUtil().setHeight(55),
          ),
          Text(
            _testQuestionList.data[index].quContent,
            style: TextStyle(
              fontSize: ScreenUtil().setSp(61),
              color: Colors.black,
            ),
          ),
          SizedBox(
            height: ScreenUtil().setHeight(90),
          ),
          Expanded(
            child: ListView.builder(
              itemCount: _optionList.length,
              itemBuilder: (BuildContext context, int ind) {
                return InkWell(
                  onTap: () {
                    setState(() {
                      if (ans[index][4] == 1) {
                        ans[index][ind] = ans[index][ind] ^ 1;
                        if(ans[index][0]==1||ans[index][1]==1||ans[index][2]==1||ans[index][3]==1)
                          _problemList[index]=1;
                        else
                          _problemList[index]=0;
                      } else {
                        _problemList[index] = 1;
                        ans[index][0] = 0;
                        ans[index][1] = 0;
                        ans[index][2] = 0;
                        ans[index][3] = 0;
                        ans[index][ind] = 1;
                      }
                      if(index==_testQuestionList.data.length-1) {
                        setState(() {
                          _nextProblem='提交';
                        });
                      }
                    });
                  },
                  child: Container(
                    margin: EdgeInsets.only(bottom: ScreenUtil().setHeight(55)),
                    decoration: BoxDecoration(
                      color: ans[index][ind] == 0
                          ? Color(0xFFF8F8F8)
                          : Color(0xFFB9EEDE),
                      borderRadius: BorderRadius.all(Radius.circular(10)),
                    ),
                    padding: EdgeInsets.all(ScreenUtil().setHeight(30)),
                    width: ScreenUtil().setWidth(992),
                    child: Text(
                      _optionList[ind],
                      style: TextStyle(
                        fontSize: ScreenUtil().setSp(60),
                        color: ans[index][ind] == 0
                            ? Colors.black45
                            : Colors.black,
                      ),
                    ),
                  ),
                );
              },
            ),
          ),
        ],
      ),
    );
  }

  Widget _pageView() {
    return Container(
      height: ScreenUtil().screenHeight -
          (ScreenUtil().screenHeight - ScreenUtil().setHeight(2140)) -
          ScreenUtil().setHeight(107 + 98),
      child: PageView.builder(
        onPageChanged: (int index) {
          currentPage = index;
          setState(() {
            progressBarValue = index;
          });
        },
        reverse: false,
        itemCount: _testQuestionList.data.length,
        physics: BouncingScrollPhysics(),
        scrollDirection: Axis.horizontal,
        controller: pageController,
        itemBuilder: (BuildContext context, int index) {
          return _problems(index);
        },
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(
      BoxConstraints(
          maxWidth: MediaQuery.of(context).size.width,
          maxHeight: MediaQuery.of(context).size.height),
      designSize: Size(1080, 2340),
    );
    if (_testQuestionList == null) {
      return Container(
        width: 0,
        height: 0,
      );
    } else {
      int len = _testQuestionList.data.length;
      if (_problemList.length == 0) {
        for (int i = 0; i < len; ++i) {
          List<int> a = [0, 0, 0, 0, 0, 0, 0];
          _problemList.add(0);
          if (_testQuestionList.data[i].quStyle == "多选题") {
            a[4] = 1;
            ans.add(a);
          } else {
            a[4] = 0;
            ans.add(a);
          }
        }
      }
      print("###" + _problemList.length.toString());
      return Stack(
        children: [
          Container(
            color: Colors.white,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                _topBar(),
                _pageView(),
              ],
            ),
          ),
          Positioned(
            bottom: 0,
            left: 0,
            child: Container(
              height: ScreenUtil().screenHeight - ScreenUtil().setHeight(2140),
              width: ScreenUtil().screenWidth,
              decoration: BoxDecoration(
                color: Colors.white,
                border: Border(
                  top: BorderSide(
                      color: Colors.black12, width: ScreenUtil().setWidth(2)),
                ),
              ),
              padding: EdgeInsets.fromLTRB(ScreenUtil().setWidth(76),
                  ScreenUtil().setHeight(44), ScreenUtil().setWidth(76), 0),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Container(
                    width: ScreenUtil().setWidth(80),
                    height: ScreenUtil().setHeight(135),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Icon(
                          MyIcons.mark,
                          size: ScreenUtil().setSp(50),
                        ),
                        Text(
                          '标记',
                          style: TextStyle(
                            fontSize: ScreenUtil().setSp(40),
                            color: Colors.black,
                          ),
                        ),
                      ],
                    ),
                  ),
                  Container(
                    width: ScreenUtil().setWidth(80),
                    height: ScreenUtil().setHeight(135),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Icon(
                          Icons.star_outline_rounded,
                          size: ScreenUtil().setSp(76),
                        ),
                        Text(
                          '收藏',
                          style: TextStyle(
                            fontSize: ScreenUtil().setSp(40),
                            color: Colors.black,
                          ),
                        ),
                      ],
                    ),
                  ),
                  InkWell(
                    onTap: () {
                      if (_nextProblem=='下一题'&&currentPage < 5) {
                        pageController.animateToPage(
                          currentPage + 1,
                          curve: Curves.ease,
                          duration: Duration(milliseconds: 500),
                        );
                      }
                      else if(_nextProblem=='提交'){
                        String s = "ABCD";
                        int num = 0;
                        List<int> ansList=[];
                        for (int i = 0; i < _testQuestionList.data.length; ++i) {
                          String tp = "";
                          for (int j = 0; j < 4; ++j)
                            if (ans[i][j] == 1) tp += s[j];
                          if (tp == _testQuestionList.data[i].quAn) {
                            ++num;
                            ansList.add(1);
                          }
                          else
                            ansList.add(0);
                        }
                        Provider.of<TestViewModel>(context, listen: false).insert(
                          widget.paId,
                          widget.stuId,
                          1.0 * num / _testQuestionList.data.length,
                          1.0 * num / _testQuestionList.data.length*100,
                          _testQuestionList.data.length,
                          num,
                          ansList,
                          widget.title,
                          int.parse(_minute),
                          int.parse(_second),
                        );
                      }
                    },
                    child: Container(
                      width: ScreenUtil().setWidth(695),
                      height: ScreenUtil().setHeight(129),
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.all(
                            Radius.circular(ScreenUtil().setHeight(129) * 0.5)),
                        gradient: LinearGradient(
                            begin: Alignment.centerLeft,
                            end: Alignment.centerRight,
                            stops: [0.0, 1.0],
                            colors: [Color(0xc42dca97), Color(0xff2dca97)]),
                      ),
                      child: Center(
                        child: Text(
                          _nextProblem,
                          style: TextStyle(
                            fontSize: ScreenUtil().setSp(52),
                            color: Colors.white,
                          ),
                        ),
                      ),
                    ),
                  )
                ],
              ),
            ),
          ),
        ],
      );
    }
  }
}
